Skip to main content

Unity3dA星寻路算法 Seeker.cs

using UnityEngine;
using System.Collections;
using AstarClasses;

public class Seeker : MonoBehaviour {
public AstarPath.Path path; //路径
public bool debugPath = false; //除错路径
public float maxAngle = 20; //最大角
public float angleCost = 2F; //角的代价
public bool removeFirst = true; //开始移动
public bool stepByStep = false; //逐步
private bool newPath = true; //新路径
public Transform endObj; //结束目标

void Update ()
{
//If a path exists and we have been calculating a new path…
if (path != null && path.path != null && newPath) {
//We are not calculating the path anymore
newPath = false;

//Convert the Node array to a Vector3 array
ArrayList a = new ArrayList (); //创建一个新的队列
for (int i=1;i<path.path.Length;i++) {
a.Add (path.path[i].vectorPos); //添加路径的向量
}
Vector3[] a2 = a.ToArray (typeof(Vector3)) as Vector3[]; //让a.ToArray的类型为Vector3[]

//Send the Vector3 array to a movement script attached to this gameObject
SendMessage("SetPoints",a2,SendMessageOptions.DontRequireReceiver); //发消息给Setpoints

}

//if (Input.GetKey ("space")) {
// StartPath (transform.position,endObj.position);
//}
}

public void OnDrawGizmos () {
if (path != null && debugPath && path.path != null) {
Gizmos.color = Color.green; //线框的颜色为绿色

for (int i=0;i<path.path.Length-1;i++) {
Node node = path.path[i] as Node; //当前节点
Node node2 = path.path[i+1] as Node; //下一个节点
Gizmos.DrawLine (node.vectorPos,node2.vectorPos); //当前节点和下一个节点之间画一条线
}
}
}

//Call this function to start calculating a path //调用这个函数开始计算路径
public void StartPath (Vector3 start, Vector3 end) { //出发的路径

//Cancel the previous path
if (path != null) {
path.error = true;
}

SendMessage("Stop",SendMessageOptions.DontRequireReceiver);//This will make the player stop这将使玩家停止
AstarPath.Path p = new AstarPath.Path (start,end,maxAngle,angleCost,stepByStep);//Create a new Path instance创建一个新的路径实例
StartCoroutine (AstarPath.StartPathYield (p));//Start a coroutine (function including yields) to calculate the path启动一个协程(功能,包括收益率)计算路径
newPath = true;//We are calculating a new path我们计算了一条新路
path = p;
}
}